package com.weijian.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weijian.common.ApiResponse;
import com.weijian.dal.dto.social.FollowRequestDTO;
import com.weijian.dal.dto.social.FollowUserDTO;
import com.weijian.dal.dto.social.LikeRequestDTO;
import com.weijian.dal.dto.social.UserStatsDTO;
import com.weijian.service.SocialService;
import com.weijian.util.SessionUserUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 社交功能控制器
 * 提供用户关注、点赞等社交功能的REST接口
 */
@RestController
@RequestMapping("/api/social")
@Tag(name = "社交功能", description = "用户关注、点赞等社交功能接口")
@Validated
public class SocialController {

    @Resource
    private SocialService socialService;

    /**
     * 关注用户
     */
    @PostMapping("/follow")
    @Operation(summary = "关注用户", description = "关注指定用户")
    public ApiResponse<Boolean> followUser(@RequestBody @Validated FollowRequestDTO request) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        boolean result = socialService.followUser(currentUserId, request.getTargetUserId());
        return ApiResponse.success(result);
    }

    /**
     * 取消关注用户
     */
    @PostMapping("/unfollow")
    @Operation(summary = "取消关注用户", description = "取消关注指定用户")
    public ApiResponse<Boolean> unfollowUser(@RequestBody @Validated FollowRequestDTO request) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        boolean result = socialService.unfollowUser(currentUserId, request.getTargetUserId());
        return ApiResponse.success(result);
    }

    /**
     * 获取当前用户的关注列表
     */
    @GetMapping("/following")
    @Operation(summary = "获取关注列表", description = "获取当前登录用户的关注列表")
    public ApiResponse<IPage<FollowUserDTO>> getFollowingList(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int size) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        IPage<FollowUserDTO> pageParam = new Page<>(page, size);
        IPage<FollowUserDTO> result = socialService.getFollowingList(currentUserId, pageParam);
        return ApiResponse.success(result);
    }

    /**
     * 获取当前用户的粉丝列表
     */
    @GetMapping("/followers")
    @Operation(summary = "获取粉丝列表", description = "获取当前登录用户的粉丝列表")
    public ApiResponse<IPage<FollowUserDTO>> getFollowersList(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int size) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        IPage<FollowUserDTO> pageParam = new Page<>(page, size);
        IPage<FollowUserDTO> result = socialService.getFollowersList(currentUserId, pageParam);
        return ApiResponse.success(result);
    }

    /**
     * 获取指定用户的关注列表
     */
    @GetMapping("/user/{userId}/following")
    @Operation(summary = "获取用户关注列表", description = "获取指定用户的关注列表")
    public ApiResponse<IPage<FollowUserDTO>> getUserFollowingList(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int size) {
        IPage<FollowUserDTO> pageParam = new Page<>(page, size);
        IPage<FollowUserDTO> result = socialService.getFollowingList(userId, pageParam);
        return ApiResponse.success(result);
    }

    /**
     * 获取指定用户的粉丝列表
     */
    @GetMapping("/user/{userId}/followers")
    @Operation(summary = "获取用户粉丝列表", description = "获取指定用户的粉丝列表")
    public ApiResponse<IPage<FollowUserDTO>> getUserFollowersList(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int size) {
        IPage<FollowUserDTO> pageParam = new Page<>(page, size);
        IPage<FollowUserDTO> result = socialService.getFollowersList(userId, pageParam);
        return ApiResponse.success(result);
    }

    /**
     * 获取共同好友列表
     */
    @GetMapping("/mutual-friends/{userId}")
    @Operation(summary = "获取共同好友", description = "获取当前用户与指定用户的共同好友列表")
    public ApiResponse<List<Long>> getMutualFriends(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        List<Long> mutualFriends = socialService.getMutualFriends(currentUserId, userId);
        return ApiResponse.success(mutualFriends);
    }

    /**
     * 检查是否已关注
     */
    @GetMapping("/is-following/{userId}")
    @Operation(summary = "检查是否已关注", description = "检查当前用户是否已关注指定用户")
    public ApiResponse<Boolean> isFollowing(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        boolean result = socialService.isFollowing(currentUserId, userId);
        return ApiResponse.success(result);
    }

    /**
     * 点赞课程
     */
    @PostMapping("/like")
    @Operation(summary = "点赞课程", description = "给指定课程点赞")
    public ApiResponse<Boolean> likeCourse(@RequestBody @Validated LikeRequestDTO request) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        boolean result = socialService.likeCourse(currentUserId, request.getCourseId());
        return ApiResponse.success(result);
    }

    /**
     * 取消点赞课程
     */
    @PostMapping("/unlike")
    @Operation(summary = "取消点赞课程", description = "取消对指定课程的点赞")
    public ApiResponse<Boolean> unlikeCourse(@RequestBody @Validated LikeRequestDTO request) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        boolean result = socialService.unlikeCourse(currentUserId, request.getCourseId());
        return ApiResponse.success(result);
    }

    /**
     * 检查是否已点赞
     */
    @GetMapping("/is-liked/{courseId}")
    @Operation(summary = "检查是否已点赞", description = "检查当前用户是否已点赞指定课程")
    public ApiResponse<Boolean> hasLikedCourse(
            @Parameter(description = "课程ID", required = true) @PathVariable Long courseId) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        boolean result = socialService.hasLikedCourse(currentUserId, courseId);
        return ApiResponse.success(result);
    }

    /**
     * 获取当前用户点赞的课程列表
     */
    @GetMapping("/liked-courses")
    @Operation(summary = "获取点赞课程列表", description = "获取当前登录用户点赞的课程列表")
    public ApiResponse<IPage<Long>> getLikedCourses(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int size) {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        IPage<Long> pageParam = new Page<>(page, size);
        IPage<Long> result = socialService.getLikedCourses(currentUserId, pageParam);
        return ApiResponse.success(result);
    }

    /**
     * 获取课程的点赞用户列表
     */
    @GetMapping("/course-likes/{courseId}")
    @Operation(summary = "获取课程点赞用户", description = "获取点赞指定课程的用户列表")
    public ApiResponse<IPage<Long>> getCourseLikes(
            @Parameter(description = "课程ID", required = true) @PathVariable Long courseId,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int size) {
        IPage<Long> pageParam = new Page<>(page, size);
        IPage<Long> result = socialService.getCourseLikes(courseId, pageParam);
        return ApiResponse.success(result);
    }

    /**
     * 获取课程点赞数
     */
    @GetMapping("/course-like-count/{courseId}")
    @Operation(summary = "获取课程点赞数", description = "获取指定课程的点赞数量")
    public ApiResponse<Long> getCourseLikeCount(
            @Parameter(description = "课程ID", required = true) @PathVariable Long courseId) {
        Long result = socialService.getCourseLikeCount(courseId);
        return ApiResponse.success(result);
    }

    /**
     * 获取用户社交统计信息
     */
    @GetMapping("/user-stats")
    @Operation(summary = "获取用户社交统计", description = "获取当前登录用户的社交统计信息")
    public ApiResponse<UserStatsDTO> getUserStats() {
        Long currentUserId = SessionUserUtil.getCurrentUserId();
        UserStatsDTO result = socialService.getUserStats(currentUserId);
        return ApiResponse.success(result);
    }

    /**
     * 获取关注排行榜
     */
    @GetMapping("/leaderboard/following")
    @Operation(summary = "关注排行榜", description = "获取关注数量排行榜")
    public ApiResponse<List<Long>> getFollowingLeaderboard(
            @Parameter(description = "数量限制", example = "10") @RequestParam(defaultValue = "10") int limit) {
        List<Long> result = socialService.getFollowingLeaderboard(limit);
        return ApiResponse.success(result);
    }

    /**
     * 获取获赞排行榜
     */
    @GetMapping("/leaderboard/likes")
    @Operation(summary = "获赞排行榜", description = "获取课程获赞数量排行榜")
    public ApiResponse<List<Long>> getLikesLeaderboard(
            @Parameter(description = "数量限制", example = "10") @RequestParam(defaultValue = "10") int limit) {
        List<Long> result = socialService.getLikesLeaderboard(limit);
        return ApiResponse.success(result);
    }

    /**
     * 手动同步Redis数据到数据库
     */
    @PostMapping("/admin/sync-redis")
    @Operation(summary = "同步Redis数据", description = "手动将Redis中的社交数据同步到数据库（管理员功能）")
    public ApiResponse<Void> syncRedisToDatabase() {
        socialService.syncRedisToDatabase();
        return ApiResponse.success(null);
    }
}